package com.jf3q.sup.controller;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.jf3q.sup.domain.Carriers;
import com.jf3q.sup.dto.CarriersPageDto;
import com.jf3q.sup.service.CarriersService;
import com.jf3q.sup.vo.ResultVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import java.util.Date;
import java.util.List;

/**
 * @author : 八九宸烨
 * @date : bug退!退!退!
 */
@RestController
public class CarriersController {

    @Autowired
    CarriersService carriersService;

    @PreAuthorize("hasAuthority('/carriers')")
    @PostMapping("/getCarriersPage")
    public ResultVo getCarriersPage(@RequestBody CarriersPageDto pageDto){
        Page page= null;
        try {
            page = carriersService.getPage(pageDto);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
        return ResultVo.success("",page);
    }

    @GetMapping("/getAll")
    public ResultVo getAll(){
        Page page= null;
        try {
            List<Carriers> list = carriersService.list();
            return ResultVo.success("",list);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    @PreAuthorize("hasAuthority('/carriers/add')")
    @PostMapping("/addCarriers")
    public ResultVo addCarriers(@RequestBody Carriers carriers){
        try {
            carriers.setCreatedAt(new Date(System.currentTimeMillis()));
            carriersService.save(carriers);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
        return ResultVo.success("", null);
    }

    @PreAuthorize("hasAuthority('/carriers/edit')")
    @PostMapping("/updateCarriers")
    public ResultVo updateCarriers(@RequestBody Carriers carriers){
        try {
            carriers.setUpdatedAt(new Date(System.currentTimeMillis()));
            carriersService.updateById(carriers);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
        return ResultVo.success("",null);
    }

    @PreAuthorize("hasAuthority('/carriers/delete')")
    @PostMapping("/delCarriers/{cId}")
    public ResultVo delCarriers(@PathVariable Integer cId){
        try {
            carriersService.removeById(cId);
        } catch (Exception e) {
            throw new RuntimeException("此信息数据与其他数据相连，请先删除与其他关联的数据再进行操作！");
        }
        return ResultVo.success("",null);
    }

    @PreAuthorize("hasAuthority('/carriers/delete')")
    @PostMapping("/delManyCarriers/{cIds}")
    public ResultVo delManyCarriers(@PathVariable Integer[] cIds){
        try {
            for (Integer cId : cIds) {
                carriersService.removeById(cId);
            }
        } catch (Exception e) {
            throw new RuntimeException("此信息数据与其他数据相连，请先删除与其他关联的数据再进行操作！");
        }
        return ResultVo.success("",null);
    }
}
